<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * 教育经历模型
 * 管理员工的教育背景信息
 */
class EducationExperience extends Model
{
    use HasFactory;

    /**
     * 表名
     */
    protected $table = 'education_experiences';

    /**
     * 可填充字段
     */
    protected $fillable = [
        'employee_id',
        'education_level',
        'degree',
        'major',
        'school_name',
        'school_type',
        'start_date',
        'end_date',
        'is_graduated',
        'gpa',
        'gpa_scale',
        'ranking',
        'academic_achievements',
        'certificate_number',
        'certificate_date',
        'certificate_type',
        'study_mode',
        'location',
        'courses',
        'description',
        'is_verified',
        'verified_by',
        'verified_at',
        'sort_order',
        'is_active',
    ];

    /**
     * 字段类型转换
     */
    protected $casts = [
        'start_date' => 'date',
        'end_date' => 'date',
        'certificate_date' => 'date',
        'verified_at' => 'date',
        'is_graduated' => 'boolean',
        'is_verified' => 'boolean',
        'is_active' => 'boolean',
        'gpa' => 'decimal:2',
        'courses' => 'array',
    ];

    /**
     * 日期字段
     */
    protected $dates = [
        'start_date',
        'end_date',
        'certificate_date',
        'verified_at',
        'created_at',
        'updated_at',
    ];

    // ============ 常量定义 ============

    public const EDUCATION_PRIMARY = 'primary';
    public const EDUCATION_JUNIOR = 'junior';
    public const EDUCATION_SENIOR = 'senior';
    public const EDUCATION_COLLEGE = 'college';
    public const EDUCATION_BACHELOR = 'bachelor';
    public const EDUCATION_MASTER = 'master';
    public const EDUCATION_DOCTOR = 'doctor';

    public const SCHOOL_PUBLIC = 'public';
    public const SCHOOL_PRIVATE = 'private';
    public const SCHOOL_INTERNATIONAL = 'international';

    public const STUDY_FULL_TIME = 'full_time';
    public const STUDY_PART_TIME = 'part_time';
    public const STUDY_DISTANCE = 'distance';

    // ============ 关联关系 ============

    /**
     * 关联员工
     */
    public function employee(): BelongsTo
    {
        return $this->belongsTo(Employee::class);
    }

    // ============ 访问器 ============

    /**
     * 获取学历标签
     */
    public function getEducationLevelLabelAttribute(): string
    {
        return match($this->education_level) {
            self::EDUCATION_PRIMARY => '小学',
            self::EDUCATION_JUNIOR => '初中',
            self::EDUCATION_SENIOR => '高中',
            self::EDUCATION_COLLEGE => '大专',
            self::EDUCATION_BACHELOR => '本科',
            self::EDUCATION_MASTER => '硕士',
            self::EDUCATION_DOCTOR => '博士',
            default => $this->education_level ?? '未知'
        };
    }

    /**
     * 获取学校类型标签
     */
    public function getSchoolTypeLabelAttribute(): string
    {
        return match($this->school_type) {
            self::SCHOOL_PUBLIC => '公立',
            self::SCHOOL_PRIVATE => '私立',
            self::SCHOOL_INTERNATIONAL => '国际',
            default => $this->school_type ?? '未知'
        };
    }

    /**
     * 获取学习方式标签
     */
    public function getStudyModeLabelAttribute(): string
    {
        return match($this->study_mode) {
            self::STUDY_FULL_TIME => '全日制',
            self::STUDY_PART_TIME => '非全日制',
            self::STUDY_DISTANCE => '远程教育',
            default => $this->study_mode ?? '未知'
        };
    }

    /**
     * 获取学习年限
     */
    public function getStudyYearsAttribute(): ?float
    {
        if (!$this->start_date) {
            return null;
        }

        $endDate = $this->end_date ?: now();
        $years = $this->start_date->diffInYears($endDate);

        return round($years, 1);
    }

    /**
     * 获取GPA百分比
     */
    public function getGpaPercentageAttribute(): ?float
    {
        if (!$this->gpa || !$this->gpa_scale) {
            return null;
        }

        return round(($this->gpa / $this->gpa_scale) * 100, 2);
    }

    /**
     * 获取证书状态
     */
    public function getCertificateStatusAttribute(): string
    {
        if (!$this->certificate_number) {
            return '无证书';
        }

        return $this->is_verified ? '已验证' : '未验证';
    }

    /**
     * 获取学校信息
     */
    public function getSchoolInfoAttribute(): string
    {
        $info = $this->school_name;

        if ($this->school_type) {
            $info .= " ({$this->school_type_label})";
        }

        if ($this->location) {
            $info .= " - {$this->location}";
        }

        return $info;
    }

    /**
     * 获取专业信息
     */
    public function getMajorInfoAttribute(): string
    {
        $info = $this->major;

        if ($this->degree) {
            $info .= " ({$this->degree})";
        }

        return $info;
    }

    // ============ 作用域 ============

    /**
     * 已毕业作用域
     */
    public function scopeGraduated($query)
    {
        return $query->where('is_graduated', true);
    }

    /**
     * 未毕业作用域
     */
    public function scopeNotGraduated($query)
    {
        return $query->where('is_graduated', false);
    }

    /**
     * 已验证作用域
     */
    public function scopeVerified($query)
    {
        return $query->where('is_verified', true);
    }

    /**
     * 未验证作用域
     */
    public function scopeNotVerified($query)
    {
        return $query->where('is_verified', false);
    }

    /**
     * 按学历筛选作用域
     */
    public function scopeByEducationLevel($query, $level)
    {
        return $query->where('education_level', $level);
    }

    /**
     * 按学校筛选作用域
     */
    public function scopeBySchool($query, $schoolName)
    {
        return $query->where('school_name', 'like', "%{$schoolName}%");
    }

    /**
     * 按专业筛选作用域
     */
    public function scopeByMajor($query, $major)
    {
        return $query->where('major', 'like', "%{$major}%");
    }

    /**
     * 按时间范围筛选作用域
     */
    public function scopeByDateRange($query, $startDate, $endDate)
    {
        return $query->whereBetween('start_date', [$startDate, $endDate]);
    }

    /**
     * 按学习方式筛选作用域
     */
    public function scopeByStudyMode($query, $mode)
    {
        return $query->where('study_mode', $mode);
    }

    // ============ 业务方法 ============

    /**
     * 验证教育经历
     */
    public function verify(string $verifiedBy): bool
    {
        $this->is_verified = true;
        $this->verified_by = $verifiedBy;
        $this->verified_at = now();

        return $this->save();
    }

    /**
     * 取消验证
     */
    public function unverify(): bool
    {
        $this->is_verified = false;
        $this->verified_by = null;
        $this->verified_at = null;

        return $this->save();
    }

    /**
     * 更新课程信息
     */
    public function updateCourses(array $courses): bool
    {
        $this->courses = $courses;
        return $this->save();
    }

    /**
     * 添加课程
     */
    public function addCourse(string $courseName, array $courseInfo = []): bool
    {
        $courses = $this->courses ?? [];
        $courses[] = array_merge(['name' => $courseName], $courseInfo);

        return $this->updateCourses($courses);
    }

    /**
     * 移除课程
     */
    public function removeCourse(string $courseName): bool
    {
        $courses = $this->courses ?? [];
        $courses = array_filter($courses, fn($course) => $course['name'] !== $courseName);

        return $this->updateCourses(array_values($courses));
    }

    // ============ 静态方法 ============

    /**
     * 获取学历等级排序
     */
    public static function getEducationLevelOrder(): array
    {
        return [
            self::EDUCATION_PRIMARY => 1,
            self::EDUCATION_JUNIOR => 2,
            self::EDUCATION_SENIOR => 3,
            self::EDUCATION_COLLEGE => 4,
            self::EDUCATION_BACHELOR => 5,
            self::EDUCATION_MASTER => 6,
            self::EDUCATION_DOCTOR => 7,
        ];
    }

    /**
     * 获取最高学历
     */
    public static function getHighestEducationLevel(array $educationLevels): ?string
    {
        if (empty($educationLevels)) {
            return null;
        }

        $order = self::getEducationLevelOrder();
        $maxOrder = 0;
        $highestLevel = null;

        foreach ($educationLevels as $level) {
            $levelOrder = $order[$level] ?? 0;
            if ($levelOrder > $maxOrder) {
                $maxOrder = $levelOrder;
                $highestLevel = $level;
            }
        }

        return $highestLevel;
    }

    /**
     * 验证学历数据
     */
    public static function validateEducationData(array $data): array
    {
        $errors = [];

        // 必填字段验证
        $requiredFields = ['employee_id', 'education_level', 'major', 'school_name', 'start_date'];
        foreach ($requiredFields as $field) {
            if (empty($data[$field])) {
                $errors[] = "{$field} 字段不能为空";
            }
        }

        // 学历等级验证
        if (!empty($data['education_level']) && !in_array($data['education_level'], array_keys(self::getEducationLevelOrder()))) {
            $errors[] = "无效的学历等级";
        }

        // GPA验证
        if (!empty($data['gpa']) && (!is_numeric($data['gpa']) || $data['gpa'] < 0)) {
            $errors[] = "GPA必须是有效的数字";
        }

        if (!empty($data['gpa_scale']) && (!is_numeric($data['gpa_scale']) || $data['gpa_scale'] <= 0)) {
            $errors[] = "GPA满分必须是有效的正数";
        }

        // 时间验证
        if (!empty($data['start_date']) && !empty($data['end_date'])) {
            $startDate = strtotime($data['start_date']);
            $endDate = strtotime($data['end_date']);

            if ($startDate && $endDate && $startDate >= $endDate) {
                $errors[] = "结束时间必须晚于开始时间";
            }
        }

        return $errors;
    }
}
